namespace CISLib.Mail
{
    using CISLib;
    using OpenSmtp.Mail;
    using System;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Timers;
    using System.Web;

    public class ScheduledMailModuleEx : IHttpModule
    {
        private EmailPool _currentEmail = null;
        private MailMessage _currentMailMessage = null;
        private HttpContext ctx = null;
        private static Timer timer;

        private Smtp CreateSmtpServer(MailConfig configer)
        {
            string str;
            string smtpAuthMode = MailConfig.SmtpAuthMode;
            smtpAuthMode = (smtpAuthMode == string.Empty) ? "None" : smtpAuthMode;
            if (((str = smtpAuthMode) != null) && (string.IsInterned(str) == "None"))
            {
                return new Smtp(MailConfig.SmtpHost, MailConfig.SmtpPort);
            }
            return new Smtp(MailConfig.SmtpHost, MailConfig.SmtpSender, MailConfig.SmtpPass, MailConfig.SmtpPort);
        }

        public void Dispose()
        {
            try
            {
                if (timer != null)
                {
                    timer.Dispose();
                    timer = null;
                    ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "dispose no null..", "", "");
                }
            }
            catch (Exception ex)
            {
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Dispose " + ex.ToString(), "", "");
            }
        }

        private void DumpMailMessage(HttpContext ctx, MailMessage mailMessage, EmailPool email)
        {
            string mailPath = Path.Combine(ctx.Server.MapPath("~"), string.Format(@"Mail\MailPool\{0}", DateTime.Today.ToShortDateString()));
            try
            {
                if (!Directory.Exists(mailPath))
                {
                    Directory.CreateDirectory(mailPath);
                }
            }
            catch (Exception)
            {
                return;
            }
            string[] addrs = new string[mailMessage.To.Count];
            int i = 0;
            foreach (EmailAddress addr in mailMessage.To)
            {
                addrs[i++] = addr.Address;
            }
            string fileName = string.Format("{0},{1}.eml", string.Join(";", addrs), email.EmailId);
            mailPath = Path.Combine(mailPath, fileName);
            mailMessage.Save(mailPath);
        }

        public void Init(HttpApplication app)
        {
            try
            {
                this.ctx = app.Context;
                if (timer == null)
                {
                    timer = new Timer();
                    timer.AutoReset = true;
                    timer.Interval = this.ScheduledMailInterval;
                    timer.Elapsed += new ElapsedEventHandler(this.timer_Elapsed);
                    timer.Start();
                }
            }
            catch (Exception ex)
            {
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Init " + ex.ToString(), "", "");
            }
        }

        private void smtpServer_EndedMessageTransfer(object sender, EventArgs e)
        {
            if (this._currentMailMessage != null)
            {
                ManageMail.RemoveEmailViaId(this._currentEmail.EmailId);
                this.DumpMailMessage(this.ctx, this._currentMailMessage, this._currentEmail);
            }
        }

        private void smtpServer_StartedMessageTransfer(object sender, EventArgs e)
        {
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                timer.Stop();
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Enter timer_Elapsed...", "", "");
                SmtpConfig.LogToText = true;
                SmtpConfig.LogPath = Path.Combine(this.ctx.Server.MapPath("~"), "Mail/SmtpLog.txt");
                MailConfig configer = MailConfig.GetInstance();
                Smtp smtpServer = this.CreateSmtpServer(configer);
                smtpServer.StartedMessageTransfer += new EventHandler(this.smtpServer_StartedMessageTransfer);
                smtpServer.EndedMessageTransfer += new EventHandler(this.smtpServer_EndedMessageTransfer);
                EmailPool[] emails = ManageMail.GetEmailsViaFlag(0, this.MailSendCountPerJob);
                for (int i = 0; (emails != null) && (i < emails.Length); i++)
                {
                    try
                    {
                        this._currentEmail = emails[i];
                        this._currentMailMessage = MailHelper.BuildMailMessageEx(configer, this._currentEmail);
                        smtpServer.SendMail(this._currentMailMessage);
                    }
                    catch (Exception ex)
                    {
                        ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Error timer_Elapsed... " + ex.ToString(), "", "");
                    }
                }
                smtpServer.Reset();
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Exit timer_Elapsed...", "", "");
                timer.Start();
            }
            catch (Exception ex)
            {
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Error in timer_Elapsed... " + ex.ToString(), "", "");
            }
        }

        private void wwwww(object sender, ElapsedEventArgs e)
        {
            try
            {
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Enter timer_Elapsed...", "", "");
                SmtpConfig.LogToText = true;
                SmtpConfig.LogPath = Path.Combine(this.ctx.Server.MapPath("~"), "Mail/SmtpLog.txt");
                MailConfig configer = MailConfig.GetInstance();
                Smtp smtpServer = this.CreateSmtpServer(configer);
                smtpServer.StartedMessageTransfer += new EventHandler(this.smtpServer_StartedMessageTransfer);
                smtpServer.EndedMessageTransfer += new EventHandler(this.smtpServer_EndedMessageTransfer);
                EmailPool[] emails = ManageMail.GetEmailsViaFlag(0, this.MailSendCountPerJob);
                for (int i = 0; (emails != null) && (i < emails.Length); i++)
                {
                    this._currentEmail = emails[i];
                    this._currentMailMessage = MailHelper.BuildMailMessageEx(configer, this._currentEmail);
                    smtpServer.SendMail(this._currentMailMessage);
                }
                smtpServer.Reset();
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Exit timer_Elapsed...", "", "");
            }
            catch (Exception ex)
            {
                ManageLog.InsertLog(Guid.NewGuid(), "Mail", DateTime.Now, "Error timer_Elapsed... " + ex.ToString(), "", "");
            }
        }

        public virtual int MailSendCountPerJob
        {
            get
            {
                return 3;
            }
        }

        public virtual long ScheduledMailInterval
        {
            get
            {
                return 0x2bf20L;
            }
        }
    }
}

